package net.libra.loader
{
	import net.libra.loader.LoadEvent;
	
	import flash.display.Bitmap;
	import flash.display.Loader;
	import flash.display.LoaderInfo;
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.IOErrorEvent;
	import flash.net.URLRequest;
	import flash.system.ApplicationDomain;
	import flash.system.LoaderContext;
	
	/**
	 * 队列加载png
	 * @author elvisjiang
	 */
	public class ImageLoader extends EventDispatcher
	{
		private var pathArray:Array;
		private var _bitmapArray:Array;
		private var currentIndex:int;
		private var loader:Loader;
		
		public function get bitmapArray():Array
		{
			return _bitmapArray;
		}
		public function ImageLoader()
		{
			this._bitmapArray = [];
			this.pathArray = [];
			this.currentIndex = -1;
		}
		public function addURL(url:String):void
		{
			for(var i:int = 0;i<pathArray.length;i++)
			{
				if(pathArray[i] == url)
				{
					return;
				}
			}
			this.pathArray.push(url);
		}
		
		public function start():void
		{
			if(this.currentIndex == -1)
			{
				this.run();
			}
		}
		private function run():void
		{
			this.currentIndex ++;
			
			var url:String = this.pathArray[this.currentIndex];
			if(url && url != "")
			{
				loader = new Loader();
				loader.contentLoaderInfo.addEventListener(Event.COMPLETE,__onResult);
				loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR,__onResult);
				try{
					loader.load(new URLRequest(url));
				}catch(error:Error)
				{
					throw new Error(error.message);
				}
			}else{
				currentIndex = -1;
				this.dispatchEvent(new LoadEvent(LoadEvent.ON_COMPLETE,null));
				if(loader){
					loader.contentLoaderInfo.removeEventListener(Event.COMPLETE,__onResult);
				}else{
					throw new Error("地址不对");
				}
				Log.info("[ImageLoader] AllItemsLoaded");
			}
		}
		private function __onResult(event:Event):void
		{
			var contentLoaderInfo:LoaderInfo = event.target as LoaderInfo;
			if(event.type == IOErrorEvent.IO_ERROR)
			{
				throw new Error("地址错误");
				this.currentIndex = -1;
				contentLoaderInfo.removeEventListener(IOErrorEvent.IO_ERROR,__onResult);
			}else if(event.type == Event.COMPLETE )
			{
				_bitmapArray.push(contentLoaderInfo.content as Bitmap);
				Log.info("[ImageLoader] Loaded " +this.pathArray[this.currentIndex]);
				this.run();
			}
		}
	}
}